package com.mtgdeckbuilder.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.mtgdeckbuilder.client.CardService;
import com.mtgdeckbuilder.server.dao.CardDAO;
import com.mtgdeckbuilder.server.entity.Card;
import com.mtgdeckbuilder.server.transformer.CardTransformer;
import com.mtgdeckbuilder.shared.dto.CardDTO;

/**
 * The server side implementation of the RPC service.
 * 
 * @author Nicolas Deslandes
 */
@SuppressWarnings("serial")
public class CardServiceImpl extends RemoteServiceServlet implements CardService {

   private static Logger logger = Logger.getLogger(CardServiceImpl.class.getName());

   @Override
   public List<CardDTO> queryDatabase(final CardDTO args, final int limit) {
      logger.finest("Call of queryDatabase(" + args + "," + limit + ")");
      final CardDAO dao = new CardDAO();
      final List<Card> entitys = dao.query(CardTransformer.dtoToEntity(args));

      final List<CardDTO> dtos = new ArrayList<CardDTO>();
      for (final Card card : entitys) {
         final CardDTO dto = CardTransformer.entityToDto(card);
         dtos.add(dto);
      }
      return dtos;
   }

   @Override
   public List<CardDTO> queryMagicSource(final CardDTO args, final int limit) {
      logger.finest("Call of queryMagicSource(" + args + "," + limit + ")");
      try {
         final MagicSource source = new WizardGathererWebsiteImpl();
         return source.query(args, limit);
      } catch (final IOException e) {
         logger.severe(e.getMessage());
         return new ArrayList<CardDTO>();
      }
   }

   /**
    * Escape an HTML string. Escaping data received from the client helps to prevent cross-site script vulnerabilities.
    * 
    * @param html the HTML string to escape
    * @return the escaped string
    */
   private String escapeHtml(final String html) {
      logger.finest("Call of escapeHtml(" + html + ")");
      if (html == null) {
         return null;
      }
      return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
   }

}
